package pl.maslany.angielski;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.BorderFactory;
import javax.swing.JTextField;

public class AppTextField extends JTextField implements KeyListener {
	
	private static final long serialVersionUID = 1L;

	private TestRecord record;
	
	public boolean isValid() {
		if (record == null) return false;
		
		for (String ans : record.correctAnwers) {
			if (ans.toLowerCase().equals(this.getText().toLowerCase())) {
				return true;
			}
		}
		return false;
	}
	
	public AppTextField(TestRecord record) {
		this.addKeyListener(this);
	}
	
	
	public void keyPressed(KeyEvent arg0) {
	}

	public void keyReleased(KeyEvent arg0) {
		boolean valid = isValid();
		if (valid) {
			this.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.GREEN));
		}
		else {
			this.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.RED));
		}
		
		if (arg0.getKeyCode() == 10 && valid) {
			((MainFrame)getRootPane().getParent()).nextTest();
			this.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.BLACK));
			this.setText("");
		}
	}

	public void keyTyped(KeyEvent arg0) {
	}

	public TestRecord getRecord() {
		return record;
	}

	public void setRecord(TestRecord record) {
		this.record = record;
	}
}
